package com.utils.util;

import com.utils.bean.EmailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Component
public class MailSend {

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private JavaMailSender mailSender;

    // 发送普通邮件
    public synchronized void sendNormalEmail(EmailDTO emailDTO) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // true-->启用带附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        doSend(emailDTO.getTargetAddress(), emailDTO.getSubject(), emailDTO.getText(), emailDTO.getAttachments(),
                mimeMessage, helper, false);
    }


    // 调用JavaMailSender接口发送邮件
    private void doSend(String[] address, String subject, String text, List<String> attachments,
                        MimeMessage mimeMessage, MimeMessageHelper helper, Boolean isThymeleafTemplate) throws MessagingException {
        helper.setFrom(mailProperties.getUsername());
        helper.setTo(address);
        helper.setSubject(subject);
        helper.setText(text, isThymeleafTemplate);
        if (!ObjectUtils.isEmpty(attachments)) {
            for (String s : attachments) {
                FileSystemResource resource = new FileSystemResource(new File(s));
                String fileName = new File(s).getName();
                helper.addAttachment(fileName, resource);
            }
        }
        try {
            mailSender.send(mimeMessage);
        } catch (MailException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
